class_name keHuDuanJianTing
extends Node

# -------------------------- 控制变量 --------------------------
var is_active: bool = false  # true开始执行，false停止，再true重新运行

# -------------------------- 配置参数 --------------------------
@export var broadcast_port_start: int = 7730   # 监听广播的起始UDP端口
@export var broadcast_port_end: int = 7740     # 监听广播的结束UDP端口
@export var scan_interval: float = 0.05         # 扫描间隔(秒)

var vectory_num_udp_port:int=0;
# -------------------------- 公开变量 --------------------------
# 当前发现的服务器字典，格式: {服务器地址: {server_name: "服务器名", server_address: "IP地址", server_port: 端口号}}
@export var discovered_servers: Dictionary = {}
# 服务器数量
@export var server_count: int = 0
@export # 最后扫描时间
var last_scan_time: float = 0
# 第一个服务器的地址信息
@export var first_server_info: Dictionary = {"address":"", "port":-1, "name": ""}
@onready var label_2: Label = $"../../UI/联机UI/VBoxContainer/客户端/扫描结果/Label2"
@onready var label: Label = $"../../UI/联机UI/VBoxContainer/客户端/扫描结果/Label"
@onready var h_box_container: HBoxContainer = $"../../UI/联机UI/VBoxContainer/客户端/扫描结果"

# -------------------------- 私有变量 --------------------------
var udp_sockets: Array = []  # 存储多个UDP socket
var scan_timer: Timer
var current_ports: Array = []  # 当前监听的端口列表
var 检查超时的服务器=100
# -------------------------- 生命周期函数 --------------------------
func _ready() -> void:
	_initialize_scanner()

# 初始化扫描器
func _initialize_scanner() -> void:
	print("=== 客户端扫描器初始化 ===")
	
	# 创建扫描定时器
	scan_timer = Timer.new()
	scan_timer.wait_time = scan_interval
	scan_timer.one_shot = false
	scan_timer.timeout.connect(_perform_scan)
	add_child(scan_timer)
	
	# 根据is_active状态决定是否启动
	if is_active:
		_start_scanning()
	else:
		print("扫描器已创建，但未激活")

# -------------------------- 控制函数 --------------------------
# 开始/恢复扫描
func start_scanning() -> void:
	if is_active:
		print("扫描器已在运行中")
		return
	h_box_container.visible=true	
	is_active = true
	_initialize_scanner()
	_start_scanning()

# 停止扫描
func stop_scanning() -> void:
	if not is_active:
		print("扫描器已停止")
		return
	h_box_container.visible=false
	is_active = false
	_stop_scanning()

# 切换扫描状态
func toggle_scanning() -> void:
	if is_active:
		stop_scanning()
	else:
		start_scanning()

# -------------------------- 内部实现 --------------------------
# 内部启动扫描
func _start_scanning() -> void:
	print("=== 启动客户端扫描器 ===")
	print("监听端口范围: ", broadcast_port_start, " - ", broadcast_port_end)
	print("扫描间隔: ", scan_interval, "秒")
	print("等待服务器广播...")
	
	# 清空之前的socket
	_close_all_sockets()
	udp_sockets.clear()
	current_ports.clear()
	
	# 创建并绑定多个端口
	for port in range(broadcast_port_start, broadcast_port_end + 1):
		var socket = PacketPeerUDP.new()
		var result = socket.bind(port)
		
		if result == OK:
			udp_sockets.append(socket)
			current_ports.append(port)
			print("✅ 成功绑定端口: ", port)
		else:
			print("❌ 无法绑定端口 ", port, " (错误码: ", result, ")")
	
	if udp_sockets.is_empty():
		print("错误: 无法绑定任何端口")
		is_active = false
		return
	
	# 启动定时器
	scan_timer.start()
	print("扫描器已启动，正在监听 ", udp_sockets.size(), " 个端口")

# 内部停止扫描
func _stop_scanning() -> void:
	print("=== 停止客户端扫描器 ===")
	
	# 停止定时器
	scan_timer.stop()
	
	# 关闭所有socket
	_close_all_sockets()
	udp_sockets.clear()
	current_ports.clear()
	
	print("扫描器已停止")

# 关闭所有socket
func _close_all_sockets() -> void:
	for socket in udp_sockets:
		if socket.is_socket_connected():
			socket.close()

# -------------------------- 公开方法 --------------------------
# 获取所有发现的服务器字典
func get_servers() -> Dictionary:
	return discovered_servers.duplicate()

# 获取所有服务器的地址列表
func get_server_addresses() -> Array:
	return discovered_servers.keys()

# 获取特定地址的服务器信息
func get_server_info(address: String) -> Dictionary:
	if discovered_servers.has(address):
		return discovered_servers[address].duplicate()
	return {"address": "", "port": 0, "name": "", "last_seen": 0}

# 获取第一个发现的服务器信息
func get_first_server() -> Dictionary:
	return first_server_info.duplicate()

# 检查是否有服务器可用
func has_servers() -> bool:
	return discovered_servers.size() > 0

# 手动执行一次扫描
func scan_now() -> void:
	if not is_active:
		print("扫描器未激活，无法执行扫描")
		return
		
	print("🔄 手动触发扫描...")
	_perform_scan()

# 清空服务器列表
func clear_servers() -> void:
	print("🗑️ 清空服务器列表")
	discovered_servers.clear()
	server_count = 0
	first_server_info = {"address": "", "port": 0, "name": ""}

# 重新启动扫描器（完全重置）
func restart_scanner() -> void:
	print("🔄 重新启动扫描器")
	_stop_scanning()
	
	# 清空服务器列表
	clear_servers()
	
	# 重新初始化
	_initialize_scanner()

# -------------------------- 扫描逻辑 --------------------------
func _perform_scan() -> void:
	if not is_active:
		return
		
	# 检查所有socket的数据包
	_check_all_sockets_for_packets()
	
	# 检查超时的服务器
	if 检查超时的服务器==0:
		_check_timeout_servers()
		检查超时的服务器=100
	检查超时的服务器-=1
	# 更新公开变量
	last_scan_time = Time.get_unix_time_from_system()
	server_count = discovered_servers.size()
	
	# 更新第一个服务器信息
	_update_first_server_info()
	
	# 显示当前发现的服务器状态
	_display_server_status()

# 检查所有socket的数据包
func _check_all_sockets_for_packets() -> void:
	if not is_active:
		return
	
	for socket in udp_sockets:
		while socket.get_available_packet_count() > 0:
			var packet = socket.get_packet()
			var port = _get_socket_port(socket)
			
			if packet.size() > 0:
				_process_packet(packet, port)

# 获取socket绑定的端口
func _get_socket_port(socket: PacketPeerUDP) -> int:
	for i in range(udp_sockets.size()):
		if udp_sockets[i] == socket:
			return current_ports[i]
	return -1

# 处理接收到的数据包
func _process_packet(packet: PackedByteArray, source_port: int) -> void:
	if not is_active:
		return
		
	var packet_string = packet.get_string_from_utf8()
	
	if packet_string.is_empty():
		return
	
	# 解析JSON
	var json = JSON.new()
	var parse_result = json.parse(packet_string)
	
	if parse_result != OK:
		print("解析错误: ", json.get_error_message())
		print("原始数据: ", packet_string)
		return
	
	var server_data = json.data
	
	# 验证服务器数据
	if not _validate_server_data(server_data):
		print("收到无效的服务器数据")
		return
	
	# 处理有效的服务器数据
	_handle_server_data(server_data, source_port)

# 验证服务器数据
func _validate_server_data(data) -> bool:
	if not is_active:
		return false
		
	if typeof(data) != TYPE_DICTIONARY:
		return false
	
	if not data.has("ip") or not data.has("tcp_port"):
		return false
	
	if data["ip"].is_empty() or data["tcp_port"] <= 0:
		return false
	
	return true

# 处理服务器数据
func _handle_server_data(server_info: Dictionary, source_port: int) -> void:
	if not is_active:
		return
		
	var server_address = server_info["ip"]
	var server_key = server_address + ":" + str(server_info["tcp_port"])
	var is_new = not discovered_servers.has(server_key)
	
	# 创建标准化的服务器信息
	var normalized_info = {
		"address": server_address,
		"port": server_info["tcp_port"],
		"name": server_info.get("name", "未知服务器"),
		"source_port": source_port,  # 记录是从哪个端口接收到的
		"last_seen": Time.get_unix_time_from_system()
	}
	
	# 更新服务器字典
	discovered_servers[server_key] = normalized_info
	
	if is_new:
		print("✅ 发现新服务器: ", normalized_info["name"], " (", server_address, ":", normalized_info["port"], ") 来自端口:", source_port)
	else:
		print("🔄 服务器更新: ", normalized_info["name"], " (", server_address, ":", normalized_info["port"], ") 来自端口:", source_port)

# 更新第一个服务器信息
func _update_first_server_info() -> void:
	if not is_active:
		return
		
	if discovered_servers.size() > 0:
		var first_key = discovered_servers.keys()[0]
		var server = discovered_servers[first_key]
		first_server_info = {
			"address": server.address,
			"port": server.port,
			"name": server.name
		}
	else:
		first_server_info = {"address": "", "port": 0, "name": ""}

	#label.text=str(address)
	
# 检查超时的服务器
func _check_timeout_servers() -> void:
	if not is_active:
		return
		
	var current_time = Time.get_unix_time_from_system()
	var timeout_threshold = scan_interval * 3  # 3倍扫描间隔视为超时
	
	var servers_to_remove = []
	
	for server_key in discovered_servers:
		var server = discovered_servers[server_key]
		var last_seen = server.get("last_seen", 0)
		
		if current_time - last_seen > timeout_threshold:
			servers_to_remove.append(server_key)
	
	# 移除超时的服务器
	for server_key in servers_to_remove:
		var server_name = discovered_servers[server_key].get("name", "未知")
		var server_address = discovered_servers[server_key].get("address", "")
		print("❌ 服务器超时移除: ", server_name, " (", server_address, ")")
		discovered_servers.erase(server_key)

# 显示服务器状态
func _display_server_status() -> void:
	if not is_active:
		return
		
	if discovered_servers.is_empty():
		print("⏳ 未发现任何服务器...")
		label_2.text = "未发现服务器"
		label.text = ""
	else:
		print("")
		print("=== 当前发现的服务器 (", discovered_servers.size(), "个) ===")
		for server_key in discovered_servers:
			var server = discovered_servers[server_key]
			var server_name = server.get("name", "未知服务器")
			var server_address = server.get("address", "")
			var server_port = server.get("port", 0)
			var source_port = server.get("source_port", 0)
			var last_seen = server.get("last_seen", 0)
			var age = Time.get_unix_time_from_system() - last_seen
			
			label.text = server_address
			label_2.text = "已找到服务器"
			
			print("  • ", server_name, " - ", server_address, ":", server_port, 
				  " (来自端口:", source_port, ", ", int(age), "秒前)")
		print("")

# -------------------------- 输入处理 --------------------------
#
# -------------------------- 资源释放 --------------------------
func _exit_tree() -> void:
	_stop_scanning()
	print("=== 客户端扫描器已停止 ===")
